package com.tianhua.javs.core.func.translate;

import com.google.common.collect.Lists;
import com.tianhua.javs.client.bean.JavsSegmentBean;
import com.tianhua.javs.core.annotations.Segment;
import com.tianhua.javs.core.constant.TagConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Description:
 * date: 2022/2/13
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Slf4j
public abstract class AbstractTranslator {
    public JavsSegmentBean translateStartReplaceFirst(String shellSegment, Class<?> beanClass, String targetSegment) {
        Segment segment = beanClass.getAnnotation(Segment.class);
        if(segment == null){
            log.warn(" not fund annotation segment.");
            return JavsSegmentBean.getInstance(shellSegment);
        }
        boolean match = false;
        if(shellSegment.trim().startsWith(segment.tag())){
            shellSegment = shellSegment.replaceFirst(segment.tag(),targetSegment);
            match = true;
        }
        JavsSegmentBean javsSegmentBean = JavsSegmentBean.getInstance(rebuildRightSign(shellSegment), "", "", segment.packageArr());
        javsSegmentBean.setMatch(match);
        return javsSegmentBean;
    }

    private String rebuildRightSign(String shellSegment){
        String [] sagArr = shellSegment.split("\\)");
        if(sagArr.length == 2){
            return shellSegment.replace(")","))");
        }
        return shellSegment;
    }

    /**
     * 获取javs 脚本代码段字符串中的范型参数信息并进行拼装得到范类型声明
     * @param javsShellSegment
     * @return
     */
    public static String getGenerateSegment(String javsShellSegment,String classTypeStr){
        if(javsShellSegment.contains(TagConstants.GT) && javsShellSegment.contains(TagConstants.LT)){
            int firstIndex = javsShellSegment.indexOf("<");
            int lastIndex = javsShellSegment.lastIndexOf(">") + 1;
            return classTypeStr + javsShellSegment.substring(firstIndex,lastIndex) ;
        }

        return classTypeStr;

    }


    /**
     * 获取javs 脚本代码段字符串中的范型参数信息并进行拼装得到范类型声明
     * @param javsShellSegment
     * @return
     */
    public  List<String> getGenerateSegment(String javsShellSegment){
        List<String> list = Lists.newArrayList();
        if(javsShellSegment.contains(TagConstants.GT) && javsShellSegment.contains(TagConstants.LT)){
            int firstIndex = javsShellSegment.indexOf("<") + 1;
            int lastIndex = javsShellSegment.lastIndexOf(">");
            String str = javsShellSegment.substring(firstIndex,lastIndex);
            if(str.contains(",")){
                String [] arr = str.split(",");
                list = Lists.newArrayList(arr);
            }else {
                list.add(str);
            }
        }

        return list;

    }
}
